import { COOKIES } from './storageTypes'
import config from '@/config'
import { msg } from '@/utils/tools'

// str: 输入字符串 length:要剩下的长度 prefix: 截取后补上的后缀
export const keepLength = (
  str: string,
  length: number,
  prefix: string = '...'
) =>
  str.length > length ? str.slice(0, length) + prefix : str.slice(0, length)

// 异步等待多少时间
export const waitTime = (time: number) =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(true)
    }, time)
  })

// 截取url hash search部分参数 返回 {hash: {}, search: {}}
export function getUrlParams(url: string) {
  let params: {
    hash: { [k: string]: string }
    search: { [k: string]: string }
  } = { hash: {}, search: {} }
  let hashIndex = url.indexOf('#')
  let searchIndex = url.indexOf('?')
  let hashStr = ''
  let searchStr = ''
  if (hashIndex > -1) {
    hashStr = url.substring(hashIndex + 1)?.split('?')[1] || ''
    url = url.substring(0, hashIndex)
  }
  if (searchIndex > -1) {
    searchStr = url.substring(searchIndex + 1)
    url = url.substring(0, searchIndex)
  }
  let hashParams = hashStr.split('&').filter((item) => !!item)
  let searchParams = searchStr.split('&').filter((item) => !!item)
  for (let i = 0; i < hashParams.length; i++) {
    let item = hashParams[i].split('=')
    params.hash[item[0]] = item[1]
  }
  for (let i = 0; i < searchParams.length; i++) {
    let item = searchParams[i].split('=')
    params.search[item[0]] = item[1]
  }
  return params
}

// 拼接链接参数 传进{a: 1, b: 2, c: 3} 返回 a=1&b=2&c=3
export function conbineUrlParams(paramsMap: AnyObject) {
  return Object.keys(paramsMap)
    .map((key) => `${key}=${paramsMap[key]}`)
    .join('&')
}

export function getUrlInfo(url: string) {
  const baseUrl = url.split('?')[0].split('#')[0]
  const hash = ~url.indexOf('#') ? '#' + url.split('#')[1].split('?')[0] : ''
  return {
    hash,
    baseUrl,
  }
}

export function addSmySign(origin_url: string) {
  if (origin_url && ~origin_url.indexOf('http')) {
    const dataParams = getUrlParams(origin_url)
    const url = getUrlInfo(origin_url)

    origin_url = `${url.baseUrl}?${conbineUrlParams({
      ...dataParams.search,
      tfsmy_source: 'tfsmy_mini',
    })}${conbineHashOrNot(url, dataParams)}`
  }

  return origin_url
}

export function conbineHashOrNot(
  url: { hash?: string; baseUrl: string },
  dataParams: {
    hash: {
      [k: string]: string
    }
    search: {
      [k: string]: string
    }
  },
  params?: Index.ServerData
) {
  if (url.hash) {
    return `${url.hash}?${conbineUrlParams({
      ...dataParams.hash,
      // tfsmy_auth: params.authType || 0,
      // tfsmy_real_name: params.sensitiveType || 0,
    })}`
  }

  return ''
}

export function throttle(fn: (this: any, arg0: any) => any, gapTime: number) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }
  let _lastTime = 0
  let callback = fn
  // 返回新的函数
  return function (this: any, arg0?: any) {

    let _nowTime = new Date().getTime()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.bind(this, ...arguments)() //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}

export function fileUpload(Filedata: any) {
  return new Promise((resolve, reject) => {
    uni.showToast({
      title: '上传中...',
      icon: 'loading',
      mask: true,
    })
    uni.uploadFile({
      url: config.uni_app_web_api_url + '/console/file/uploadFile',
      filePath: Filedata.tempFilePath,
      header: { cookie: uni.getStorageSync(COOKIES) || '' },
      name: 'file',
      success: (res: any) => {
        const data = JSON.parse(res.data)
        uni.hideLoading()
        if (res.statusCode === 200 && data.success) {
          uni.showToast({
            title: '上传成功',
            icon: 'none',
          })
          resolve(JSON.parse(res.data))
        } else {
          reject(data)
          uni.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000,
          })
        }
      },
      fail: (err) => {
        uni.hideLoading()
        reject(err)
      },
    })
  })
}

export function systemInfo() {
  /****************** 所有平台共有的系统信息 ********************/
  // 设备系统信息
  let systemInfomations = uni.getSystemInfoSync()

  // 机型适配比例系数
  let scaleFactor = undefined
  // 当前机型-屏幕宽度
  let windowWidth = undefined
  if (systemInfomations && systemInfomations.windowWidth) {
    scaleFactor = 750 / systemInfomations.windowWidth
    windowWidth = systemInfomations.windowWidth * scaleFactor //rpx
  }

  // 当前机型-屏幕高度
  let windowHeight = undefined
  if (systemInfomations && systemInfomations.windowHeight && scaleFactor) {
    windowHeight = systemInfomations.windowHeight * scaleFactor //rpx
  }

  // 状态栏高度
  let statusBarHeight = undefined
  if (systemInfomations && systemInfomations.statusBarHeight && scaleFactor) {
    statusBarHeight = systemInfomations.statusBarHeight * scaleFactor //rpx
  }

  // 导航栏高度  注意：此导航栏高度只针对微信小程序有效 其他平台如自定义导航栏请使用：状态栏高度+自定义文本高度
  let navHeight = 0 //rpx

  /****************** 微信小程序头部胶囊信息 ********************/
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  let menuButtonHeight = undefined
  let menuButtonWidth = undefined
  let menuButtonTop = undefined
  let menuButtonLeft = undefined
  let menuButtonBottom = undefined
  let menuButtonRight = undefined
  if (scaleFactor) {
    // 胶囊高度
    menuButtonHeight = menuButtonInfo.height * scaleFactor //rpx
    // 胶囊宽度
    menuButtonWidth = menuButtonInfo.width * scaleFactor //rpx
    // 胶囊上边界的坐标
    menuButtonTop = menuButtonInfo.top * scaleFactor //rpx
    // 胶囊右边界的坐标
    menuButtonRight = menuButtonInfo.right * scaleFactor //rpx
    // 胶囊下边界的坐标
    menuButtonBottom = menuButtonInfo.bottom * scaleFactor //rpx
    // 胶囊左边界的坐标
    menuButtonLeft = menuButtonInfo.left * scaleFactor //rpx
  }

  if (menuButtonHeight && menuButtonTop && statusBarHeight) {
    // 微信小程序中导航栏高度 = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
    navHeight = menuButtonHeight + (menuButtonTop - statusBarHeight) * 2
  }

  // #endif

  // #ifdef MP-WEIXIN
  return {
    scaleFactor,
    windowHeight,
    windowWidth,
    statusBarHeight,
    menuButtonHeight,
    menuButtonWidth,
    menuButtonTop,
    menuButtonRight,
    menuButtonBottom,
    menuButtonLeft,
    navHeight,
  }
  // #endif
}
